#include "Geometry.h"
#include "Shaders.h"
#include "Muzzy A Wrappers\D3DManager.h"


Geometry::Geometry(void)
{
	pShaders	= Shaders::getInstance();
	m_fRotation	= 0;
	m_ColorMask	= Color(1,1,1,1);

	m_vTexCoords[0].x = 0;
	m_vTexCoords[0].y = 0;
	m_vTexCoords[1].x = 1;
	m_vTexCoords[1].y = 0;
	m_vTexCoords[2].x = 1;
	m_vTexCoords[2].y = 1;
	m_vTexCoords[3].x = 0;
	m_vTexCoords[3].y = 1;
}


Geometry::~Geometry(void)
{
}

void Geometry::Render(const Matrix &mTransform)
{
	// Declarations
	IDirect3DDevice9 *dev = D3DManager::getInstance()->getDevice();
	Matrix			rot;
	unsigned		passes = 0;

	// Create the rotation matrix
	RotateZ(rot,m_fRotation);

	// Set shader parameters
	pShaders->getActiveShader()->SetMatrix(pShaders->getMVPHandle(),&(mTransform * rot));
	pShaders->getActiveShader()->SetTexture(pShaders->getTextureHandle(),m_pTexture);
	pShaders->getActiveShader()->SetValue(pShaders->getTexCoordHandle(),m_vTexCoords,sizeof(m_vTexCoords));
	pShaders->getActiveShader()->SetValue(pShaders->getColorMaskHandle(),&m_ColorMask,sizeof(m_ColorMask));

	// Begin drawing
	pShaders->getActiveShader()->Begin(&passes,0);
	pShaders->getActiveShader()->BeginPass(0);
	
	// Draw the textured shape
	dev->SetVertexDeclaration(m_pVertDecl);
	dev->SetStreamSource(0,m_pVertBuff,0,sizeof(Vertex));
	dev->SetIndices(m_pIndexBuff);
	dev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,4,0,2);

	// End drawing
	pShaders->getActiveShader()->EndPass();
	pShaders->getActiveShader()->End();
}

void Geometry::setSrcRect(const RECT &srcRect)
{
	// Declarations
	float	fLeft	= (float)srcRect.left;
	float	fRight	= (float)srcRect.right;
	float	fTop	= (float)srcRect.top;
	float	fBottom	= (float)srcRect.bottom;

	// Turn screen coordinates to clip space coordinates
	fLeft	/= m_nImageWidth;
	fRight	/= m_nImageWidth;
	fTop	/= m_nImageHeight;
	fBottom	/= m_nImageHeight;

	// Copy the new texture coordinates to the array of texture coordinates
	m_vTexCoords[0] = Vector2(fLeft,fTop);
	m_vTexCoords[1] = Vector2(fRight,fTop);
	m_vTexCoords[2] = Vector2(fRight,fBottom);
	m_vTexCoords[3] = Vector2(fLeft,fBottom);

	// Calculate new width and height of the vertex buffer
	m_fWidth	= (float)(srcRect.right - srcRect.left)/D3DManager::getInstance()->getWndWidth();
	m_fHeight	= (float)(srcRect.bottom - srcRect.top)/D3DManager::getInstance()->getWndHeight();

	// Make new verts for the vertex buffer
	Vertex verts[] = 
	{
		{ 0, Vector3( -m_fWidth, m_fHeight,0) }, // 0
		{ 1, Vector3(  m_fWidth, m_fHeight,0) }, // 1
		{ 2, Vector3(  m_fWidth,-m_fHeight,0) }, // 2
		{ 3, Vector3( -m_fWidth,-m_fHeight,0) }  // 3
	};

	// Copy the new verts to the vertex buffer on the v-card
	void *vram = nullptr;
	m_pVertBuff->Lock(0,0,&vram,0);
	memcpy(vram,verts,sizeof(verts));
	m_pVertBuff->Unlock();
}